<?php

class OrderController extends AController
{
    public $_model;

    public function filters()
    {
        return array(
            'accessControl',
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('view', 'create', 'confirm', 'success', 'failure', 'payment', 'finalize', 'detail'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('admin', 'delete', 'update', 'view', 'slip', 'invoice'),
                'users' => array('*'),
            ),
            array('deny', // deny all other users
                'users' => array('*'),
            ),
        );
    }

    public function actionSlip($id)
    {
        if ($model = $this->loadModel($id))
            $this->render(Shop::module()->slipView, array('model' => $model));
    }

    public function loadModel()
    {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Order::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    public function actionInvoice($id)
    {
        if ($model = $this->loadModel($id))
            $this->render(Shop::module()->invoiceView, array('model' => $model));
    }

    public function beforeAction($action)
    {
        return parent::beforeAction($action);
    }

    public function actionView()
    {
        $this->render('view', array(
            'model' => $this->loadModel(),
        ));
    }

    public function actionConfirm($customer = null)
    {
        if (!$customer)
            $customer = Yii::app()->user->getState('customer_id');

        if (!$customer) {
            $this->render('/customer/create', array(
                'action' => array('//shop/customer/create')));
            Yii::app()->end();
        }
        $cart = Shop::getCartContent();
        $this->render('/order/confirm', array(
            'action' => array('//shop/order/process-payment'),
            'products' => $cart
        ));
    }

    public function actionAdmin()
    {
        if (Yii::app()->session['order_keyword']) {
            unset(Yii::app()->session['order_keyword']);
        }
        $sort = 'ordering_date desc';

        $criteria = new CDbCriteria();
        if (!empty($_POST['order_keyword'])) {
            $keyword = $_POST['order_keyword'];
        }
        $criteria->order = $sort;

        $item_count = Order::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('admin', array(
            'model' => Order::model()->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => Yii::app()->params['listPerPage'],
            'items_count' => $item_count,
            'pages' => $pages,
            'sort' => $sort
        ));
    }

    public function actionUpdate($id, $status = null)
    {
        $model = $this->loadModel();

        if(!empty($status)) {
            $model->status = $status;
            if($model->save()) {
                echo 'success';
            } else {
                echo 'fail';
            }

        }
    }

    public function actionDelete()
    {
        if(!empty($_POST['ids'])) {
            foreach($_POST['ids'] as $order) {
                Order::model()->deleteAll("order_id='" . $order . "'");
            }
            Yii::app()->user->setFlash('message', "Xóa đơn hàng thành công!");
            $this->redirect('/admin/order/admin');
        }
    }
    
    public function actionDetail($id)
    {
    	$order = Order::model()->findByPk($id);
    	
    	$criteria = new CDbCriteria();
    	$criteria->condition = 'order_id = ' . $id;
    	$products = OrderPosition::model()->findAll($criteria);
		
    	$shippingCountry = new ShippingCountry();
    	if($order->deliveryAddress->country) {
            $country = $order->deliveryAddress->country;
        } else {
            $country = $order->billingAddress->country;
        }
        
    	$this->render('/order/detail', array(
            'order' => $order,
    		'products' => $products,
    		'country' => $country
        ));
    }
}
